/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.cqcis.uip.base.framework.service.impl;

import org.apache.mina.common.IoSession;

import com.cqcis.uip.base.framework.core.RegisteredService;
import com.cqcis.uip.base.framework.utils.RegisterServiceLogUtil;
import com.cqcis.uip.base.logadaptor.LogConfiguration;
import com.cqcis.uip.base.logadaptor.ObjectWriter;
import com.cqcis.uip.base.logadaptor.impl.LogObjectAppender;

/**
 * @author huangmy
 * @date   2008-4-11
 */
public class RegisterServicePrintlogConsole {
	public final static String LOGAPPENDER_FINDKEY = RegisterServicePrintlogConsole.class.getName() + "_LOGAPPENDER_FINDKEY";
	public final static String LOGCONFIG_FINDKEY = RegisterServicePrintlogConsole.class.getName() + "_LOGCONFIG_FINDKEY";
	private LogObjectAppender appender; // 日志组件
	private RegisteredService rs; // 注册服务
	private String level; // 日志级别
	private IoSession session; // MINA session
		
	/**
	 * constructor
	 * 
	 * @param bundleId 注册服务 bundle id
	 * @param session 写session
	 */
    public RegisterServicePrintlogConsole(RegisteredService rs, String level, IoSession session, final SessionOutput sot, boolean quieted, String quietPackages) {    	
    	this.appender = new LogObjectAppender(new ObjectWriter() {
    		public void write(Object o) {
    			sot.write(o);
    		}
    	}, level, rs.getLogConfiguration().getConversionPattern(), quieted, quietPackages);
    	
    	this.rs = rs;
    	this.level = level;
    	this.session = session;
    	
    	// 设置日志组件属性
    	// 新建一个格式转换实例    	
    	this.appender.setName(session + "_Appender");
    }
    
    /**
     * 开始输出
     * 
     */
    public void print() {    	
    	// 新建一个面向session的日志配置
    	LogConfiguration sessionConfig = new LogConfiguration();
    	sessionConfig.setLevel(this.level);    	
    	sessionConfig.setLogAppenderType(LogConfiguration.LOGAPPENDER_TYPE_LOGOBJECT);    	
    	sessionConfig.setLogObjectAppender(this.appender); // 设置日志组件
    	
    	RegisterServiceLogUtil.addLogToRS(this.rs, sessionConfig); // 添加日志配置到服务中
    	
    	this.session.setAttribute(LOGCONFIG_FINDKEY, sessionConfig);    	
    }
    
    /**
     * 关闭
     * 
     */
    public void close() {
    	LogConfiguration sessionConfig = (LogConfiguration)this.session.getAttribute(LOGCONFIG_FINDKEY);
    	
    	RegisterServiceLogUtil.removeLogToRS(this.rs, sessionConfig);// 删除日志配置
    	// 关闭
    	if (appender != null) {
    		appender.close();
    	}
    }
    
    public RegisteredService getRegisteredService() {
    	return this.rs;
    }
}
